<?php
namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\model\Article as ArticleModel;

/**
 * 文章管理
 * @package app\admin\controller
 */
class Article extends AdminBase
{
    private $model=null;
    public function _initialize()
    {
        if (is_null($this->model)) {
            $this->model = new ArticleModel;
        }
    }
    # 全部文章列表
    public function index()
    {
        $data=$this->model->getAllData();
        $this->assign('data', $data);
        return $this->fetch();
    }
    # 文章添加
    public function add()
    {
        if (!request()->isAjax()) {
            $category=model('Category')->getDataByWhere(['status'=>1]);
            $tag=model('Tag')->getAllData();
            $this->assign('category_list', $category);
            $this->assign('tag_list', $tag);
            return $this->fetch();
        }
        $data=input('post.');
        $result=$this->model->addData($data);
        if (is_array($result)) {
            return json(['errno'=>1,'msg'=>$result['msg']]);
        }
        if (!$result) {
            return json(['errno'=>1,'msg'=>'添加文章时发生错误']);
        }
        $preg='/uploads\/\d*\/\w*\.[jpg|jpeg|png|bmp|gif]*/i';
        $imgPathArr=getImgPath($data['content'], $preg);
        model('ArticlePic')->addData($result, $imgPathArr);
        # 推送百度
        if (config('?web.baidu_site_url')) {
            baidu_site($result);
        }
        # 生成sitemap.xml
        $list=model('Article')->getDataByWhere(['status'=>1], 'id DESC');
        $sitemap = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<urlset>\r\n";
        foreach ($list as $v) {
            $sitemap .= "    <url>\r\n"."        <loc>".url('index/index/article', ['id'=>$v['id']], '', true)."</loc>\r\n"."        <lastmod>".$v['create_time']."</lastmod>\r\n        <changefreq>weekly</changefreq>\r\n        <priority>0.8</priority>\r\n    </url>\r\n";
        }
        $sitemap .= '</urlset>';
        file_put_contents('./sitemap.xml', $sitemap);
        return json(['errno'=>0,'msg'=>'添加文章成功']);
    }
    # 编辑文章
    public function edit()
    {
        if (!request()->isAjax()) {
            $id=input('param.id');
            $article=ArticleModel::get($id);
            if (!$article) {
                $this->error('未找到相关数据');
            }
            $category=model('Category')->getDataByWhere(['status'=>1]);
            $tag=model('Tag')->getAllData();
            $tids=explode(',', $article['tid']);
            $this->assign('data', $article->getData());
            $this->assign('category_list', $category);
            $this->assign('tag_list', $tag);
            $this->assign('tids', $tids);
            return $this->fetch();
        }
        $id=input('param.id');
        $data=input('post.');
        $result=$this->model->editData(['id'=>$id], $data);
        if (is_array($result)) {
            return json(['errno'=>1,'msg'=>$result['msg']]);
        }
        if (!$result) {
            return json(['errno'=>1,'msg'=>'编辑文章时发生错误']);
        }
        $preg='/uploads\/\d*\/\w*\.[jpg|jpeg|png|bmp|gif]*/i';
        $imgPathArr=getImgPath($data['content'], $preg);
        # 删除无效图片冗余
        $oldPathArr=model('ArticlePic')->getImgArr($id);
        foreach ($oldPathArr as $value) {
            if (!in_array($value, $imgPathArr )) {
                delDirAndFile($value);
            }
        }
        model('ArticlePic')->delData($id);
        # 添加新图片路径
        model('ArticlePic')->addData($id, $imgPathArr);
        return json(['errno'=>0,'msg'=>'编辑文章成功']);
    }
    # 删除文章
    public function del()
    {
        if (!request()->isAjax()) {
            $this->redirect('admin/article/index');
        } else {
            $data=input('post.');
            $result=$this->model->delData($data['id']);
            if (!$result) {
                return json(['errno'=>1,'msg'=>'文章删除时发生错误']);
            }
            return json(['errno'=>0,'msg'=>'文章删除成功']);
        }
    }
    # 已删除文章
    public function deleted()
    {
        $data=$this->model->getAllData(true);
        $this->assign('data', $data);
        return $this->fetch();
    }
    # 恢复已删除文章
    public function restore()
    {
        if (!request()->isAjax()) {
            $this->redirect('admin/article/index');
        } else {
            $data=input('post.');
            $result=$this->model->restoreData($data['id']);
            if (!$result) {
                return json(['errno'=>1,'msg'=>'文章恢复时发生错误']);
            }
            return json(['errno'=>0,'msg'=>'文章恢复成功']);
        }
    }
    # 清空已删除文章
    public function clear()
    {
        if (!request()->isAjax()) {
            $this->redirect('admin/article/index');
        }
        $data=input('post.');
        $result=$this->model->delData($data['id'], true);
        if (!$result) {
            return json(['errno'=>1,'msg'=>'文章清除时发生错误']);
        }
        # 清除图片冗余
        if (is_array($data['id'])) {
            foreach ($data['id'] as $value) {
                $imgPathArr=model('ArticlePic')->getImgArr(intval($value));
                foreach ($imgPathArr as $val) {
                    delDirAndFile($val);
                }
                model('ArticlePic')->delData(intval($value));
            }
        } else {
            $imgPathArr=model('ArticlePic')->getImgArr(intval($data['id']));
            foreach ($imgPathArr as $val) {
                delDirAndFile($val);
            }
            model('ArticlePic')->delData(intval($data['id']));
        }
        # 清除评论
        if (is_array($data['id'])) {
            foreach ($data['id'] as $value) {
                model('Comment')->where('aid', intval($value))->delete();
            }
        }
        model('Comment')->where('aid', intval($data['id']))->delete();
        return json(['errno'=>0,'msg'=>'文章清除成功']);
    }
    # 上传图片
    public function upload()
    {
        $file = request()->file('image');
        $info = $file->validate(['size'=>1024*1024*2,'ext'=>'jpg,jpeg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads');
        if (!$info) {
            return json(['errno'=>1,'msg'=>$info->getError()]);
        }
        $url= DS .'uploads'. DS .$info->getSaveName();
        $url=str_replace("\\", "/", $url);
        $shortUrl=$info->getSaveName();
        return json(['errno'=>0,'msg'=>'上传成功','url'=>$url,'short'=>$shortUrl]);
    }
}
